<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">






  
  
    
      
    
    
      
    
  <script src="https://cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
  <link href="https://cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-flash.min.css" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















  

<link href="https://cdn.bootcss.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.3.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.3.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.3.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="redux之applyMiddlewareredux 函数式写法相当多，所以在 applyMiddleware 处理多个中间执行顺序的写法也是比较绕和难懂的。redux 的中间件用切面的思想，让第三方的中间件切入到 reducer 处理 action 之前，做一些处理比如 log 之类的。applyMiddleware 则是把众多的中间件汇聚在一起，一层一层地去增强了原本生成的store 上的 d">
<meta name="keywords" content="react,redux,源码">
<meta property="og:type" content="article">
<meta property="og:title" content="redux之applyMiddleware">
<meta property="og:url" content="http://yoursite.com/2018/09/03/redux之applyMiddleware/index.html">
<meta property="og:site_name" content="三月的米店">
<meta property="og:description" content="redux之applyMiddlewareredux 函数式写法相当多，所以在 applyMiddleware 处理多个中间执行顺序的写法也是比较绕和难懂的。redux 的中间件用切面的思想，让第三方的中间件切入到 reducer 处理 action 之前，做一些处理比如 log 之类的。applyMiddleware 则是把众多的中间件汇聚在一起，一层一层地去增强了原本生成的store 上的 d">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-11-29T02:09:38.101Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="redux之applyMiddleware">
<meta name="twitter:description" content="redux之applyMiddlewareredux 函数式写法相当多，所以在 applyMiddleware 处理多个中间执行顺序的写法也是比较绕和难懂的。redux 的中间件用切面的思想，让第三方的中间件切入到 reducer 处理 action 之前，做一些处理比如 log 之类的。applyMiddleware 则是把众多的中间件汇聚在一起，一层一层地去增强了原本生成的store 上的 d">






  <link rel="canonical" href="http://yoursite.com/2018/09/03/redux之applyMiddleware/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>redux之applyMiddleware | 三月的米店</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">三月的米店</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">今儿不吃饭</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/09/03/redux之applyMiddleware/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Mark Lee">
      <meta itemprop="description" content="折腾小久的博客,在 2018-08-01 终于基本成型啦，以后就常驻啦">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="三月的米店">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">redux之applyMiddleware
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-09-03 21:39:05" itemprop="dateCreated datePublished" datetime="2018-09-03T21:39:05+08:00">2018-09-03</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-11-29 10:09:38" itemprop="dateModified" datetime="2018-11-29T10:09:38+08:00">2018-11-29</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/前端/" itemprop="url" rel="index"><span itemprop="name">前端</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="redux之applyMiddleware"><a href="#redux之applyMiddleware" class="headerlink" title="redux之applyMiddleware"></a>redux之applyMiddleware</h1><p><code>redux</code> 函数式写法相当多，所以在 <code>applyMiddleware</code> 处理多个中间执行顺序的写法也是比较绕和难懂的。<code>redux</code> 的中间件用切面的思想，让第三方的中间件切入到 <code>reducer</code> 处理 <code>action</code> 之前，做一些处理比如 <code>log</code> 之类的。<code>applyMiddleware</code> 则是把众多的中间件汇聚在一起，一层一层地去增强了原本生成的<code>store</code> 上的 <code>dispath</code> 的功能。</p>
<h2 id="用法"><a href="#用法" class="headerlink" title="用法"></a>用法</h2><p>先看下怎么使用这个 <code>api</code>：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; createStore, applyMiddleware &#125; <span class="keyword">from</span> <span class="string">'redux'</span></span><br><span class="line"><span class="keyword">import</span> todos <span class="keyword">from</span> <span class="string">'./reducers'</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">logger</span>(<span class="params">&#123; getState &#125;</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function">(<span class="params">next</span>) =&gt;</span> (action) =&gt; &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'will dispatch'</span>, action)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 调用 middleware 链中下一个 middleware 的 dispatch。</span></span><br><span class="line">    <span class="keyword">let</span> returnValue = next(action)</span><br><span class="line"></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'state after dispatch'</span>, getState())</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 一般会是 action 本身，除非</span></span><br><span class="line">    <span class="comment">// 后面的 middleware 修改了它。</span></span><br><span class="line">    <span class="keyword">return</span> returnValue</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> store = createStore(</span><br><span class="line">  todos,</span><br><span class="line">  [ <span class="string">'Use Redux'</span> ],</span><br><span class="line">  applyMiddleware(logger)</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">store.dispatch(&#123;</span><br><span class="line">  type: <span class="string">'ADD_TODO'</span>,</span><br><span class="line">  text: <span class="string">'Understand the middleware'</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// (将打印如下信息:)</span></span><br><span class="line"><span class="comment">// will dispatch: &#123; type: 'ADD_TODO', text: 'Understand the middleware' &#125;</span></span><br><span class="line"><span class="comment">// state after dispatch: [ 'Use Redux', 'Understand the middleware' ]</span></span><br></pre></td></tr></table></figure>
<p>官网的这个例子大概说明了 <code>applyMiddleware</code> 的用法了，这里用 <code>let store = createStore(todos, [ &#39;Use Redux&#39; ],applyMiddleware(logger))</code> 生成了一个新的store，同样的也可以用 <code>let newStore = applyMiddleware(mid1, mid2, mid3, ...)(createStore)(reducer, initialState);</code> 的方式生成 <code>store</code>。<code>applyMiddleware</code> 返回一个 <code>store</code> 的 <code>enhancer</code> 然后生成增强后的 <code>createStore</code> ，部分细节可以参照 <code>createStore</code> 中的一小段代码：</p>
<p><code>./createStore.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (<span class="keyword">typeof</span> enhancer !== <span class="string">'undefined'</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> enhancer !== <span class="string">'function'</span>) &#123;</span><br><span class="line">        <span class="comment">// enhancer 不是函数就报错</span></span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'Expected the enhancer to be a function.'</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> enhancer(createStore)(reducer, preloadedState)</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<h2 id="源码"><a href="#源码" class="headerlink" title="源码"></a>源码</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">applyMiddleware</span>(<span class="params">...middlewares</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="params">createStore</span> =&gt;</span> (...args) =&gt; &#123;</span><br><span class="line">    <span class="keyword">const</span> store = createStore(...args)</span><br><span class="line">    <span class="keyword">let</span> dispatch = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(</span><br><span class="line">        <span class="string">`Dispatching while constructing your middleware is not allowed. `</span> +</span><br><span class="line">          <span class="string">`Other middleware would not be applied to this dispatch.`</span></span><br><span class="line">      )</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> middlewareAPI = &#123;</span><br><span class="line">      getState: store.getState,</span><br><span class="line">      dispatch: <span class="function">(<span class="params">...args</span>) =&gt;</span> dispatch(...args)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> chain = middlewares.map(<span class="function"><span class="params">middleware</span> =&gt;</span> middleware(middlewareAPI))</span><br><span class="line">    dispatch = compose(...chain)(store.dispatch)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// const middle1 = next =&gt; action =&gt; next(action)</span></span><br><span class="line">    <span class="comment">// const middle2 = next =&gt; action =&gt; next(action)</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// dispatch = compose(middle1, middle2)(store.dispatch) = middle1(middle2(store.dispatch))</span></span><br><span class="line">    <span class="comment">// dispatch(actions) = middle1(middle2(store.dispatch))(actions)</span></span><br><span class="line">    <span class="comment">// middle2(store.dispatch) = action =&gt; store.dispath(action)</span></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      ...store,</span><br><span class="line">      dispatch</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上来返回一个接收 <code>createStore</code>做为参数的函数，调用这个<code>createStore</code> 去生成对应的 <code>store</code>，之前也提到了<code>applyMiddleware</code> 主要目的是为了增强 <code>dispatch</code>的功能，所以最后是用拓展运算符返回了原本store上的属性以及增强过的<code>dispatch</code>。</p>
<h3 id="细节"><a href="#细节" class="headerlink" title="细节"></a>细节</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">(...args) =&gt; &#123;</span><br><span class="line">    <span class="keyword">const</span> store = createStore(...args)</span><br><span class="line">    <span class="keyword">let</span> dispatch = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(</span><br><span class="line">        <span class="string">`Dispatching while constructing your middleware is not allowed. `</span> +</span><br><span class="line">          <span class="string">`Other middleware would not be applied to this dispatch.`</span></span><br><span class="line">      )</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> middlewareAPI = &#123;</span><br><span class="line">      getState: store.getState,</span><br><span class="line">      dispatch: <span class="function">(<span class="params">...args</span>) =&gt;</span> dispatch(...args)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> chain = middlewares.map(<span class="function"><span class="params">middleware</span> =&gt;</span> middleware(middlewareAPI))</span><br><span class="line">    dispatch = compose(...chain)(store.dispatch)</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      ...store,</span><br><span class="line">      dispatch</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>中间件的签名是这样的 <code>({dispatch, getStore}) =&gt; next =&gt; action =&gt; {// 一些第三方中间件的处理}</code>，这里对整个<code>middlewares</code> 数组进行了一次 <code>map</code> 给每一个中间件传入 <code>middlewareAPI</code> 进行一次调用，可以看做是进行了一次剥皮，这样chain里面存的就都是 <code>next =&gt; action =&gt; {// 一些第三方中间件的处理}</code> 这样签名的函数了。最关键的一步来了，<code>dispatch = compose(...chain)(store.dispatch)</code> 用 <code>compose</code> 把<code>chain</code> 内部的函数全部组合起来，接受最原始的 <code>store.dispatch</code>，生成一个增强后的 <code>dispatch</code> 。讲清楚这一行代码，就能搞明白 <code>redux</code> 的中间件干了什么事情。</p>
<h3 id="特别的一行代码"><a href="#特别的一行代码" class="headerlink" title="特别的一行代码"></a>特别的一行代码</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dispatch = compose(...chain)(store.dispatch)</span><br></pre></td></tr></table></figure>
<p>我们先假设传给了 <code>applyMiddleware</code> 这样的参数：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">const</span> middleware1 = <span class="function">(<span class="params">&#123;dispatch, getStore&#125;</span>) =&gt;</span> next =&gt; <span class="function"><span class="params">action</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`middleware1 start`</span>)</span><br><span class="line">    next(action)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`middleware1 end`</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> middleware2 = <span class="function">(<span class="params">&#123;dispatch, getStore&#125;</span>) =&gt;</span> next =&gt; <span class="function"><span class="params">action</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`middleware2 start`</span>)</span><br><span class="line">    next(action)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`middleware2 end`</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> enhancer = applyMidleware([middleware1, middleware2])</span><br></pre></td></tr></table></figure>
<p>到了上述这行代码的时候，<code>chain</code> 是这个样子了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">const</span> m1 = <span class="function"><span class="params">next</span> =&gt;</span> action =&gt; &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`middleware1 start`</span>)</span><br><span class="line">        next(action)</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`middleware1 end`</span>)</span><br><span class="line">    &#125;</span><br><span class="line"><span class="keyword">const</span> m2 = <span class="function"><span class="params">next</span> =&gt;</span> action =&gt; &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`middleware2 start`</span>)</span><br><span class="line">        next(action)</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`middleware2 end`</span>)</span><br><span class="line">    &#125;</span><br><span class="line">chain = [m1, m2]</span><br></pre></td></tr></table></figure>
<p>结合之前提到的 <code>compose</code> 组合函数，所以这行代码变形成这样：<code>dispatch = m1(m2(store.dispatch))</code>。这个时候假设需要<code>dispatch</code> 一个 <code>anAction</code> ，就会变成这样 <code>m1(m2(store.dispatch))(anAction)</code>。对于m1而言，<code>m2(store.dispatch)</code> 就是他的 <code>next</code> 参数，当 <code>m1</code> 执行到 <code>next(action)</code>的时候，相当于这时候调用了<code>m2(store.dispatch)(action)</code>, 然后进入到<code>m2</code>中间件的逻辑，此时<code>m2</code>中间件接受的 <code>next</code> 正是原本的 <code>store.dispatch</code>，运行到<code>m2</code> 内部的 <code>next(action)</code> 的时候，这时候才去真正的用<code>store.dispatch</code> 去处理这个 <code>action</code>。每一次调用 <code>next</code> 就把这个中间件的控制权交给下一个中间件。</p>
<p>这就有种俄罗斯套娃一样，一层一层地嵌套，<code>action</code> 经过多层的处理，最终到达最里层的才真正地被<code>dispatch</code> 。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p><code>applyMiddleware</code> 最为核心就是 <code>dispatch = compose(...chain)(store.dispatch)</code>，由此我想到了 <code>koa</code> 中间件的机制，有所相似，实现也不太一样。</p>

      
    </div>

    

    
    
    

    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/react/" rel="tag"><i class="fa fa-tag"></i> react</a>
          
            <a href="/tags/redux/" rel="tag"><i class="fa fa-tag"></i> redux</a>
          
            <a href="/tags/源码/" rel="tag"><i class="fa fa-tag"></i> 源码</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/26/维生素指北/" rel="next" title="维生素指北">
                <i class="fa fa-chevron-left"></i> 维生素指北
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/09/12/react使用指南/" rel="prev" title="react使用指南">
                react使用指南 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Mark Lee</p>
              <p class="site-description motion-element" itemprop="description">折腾小久的博客,在 2018-08-01 终于基本成型啦，以后就常驻啦</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">26</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">4</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">20</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#redux之applyMiddleware"><span class="nav-number">1.</span> <span class="nav-text">redux之applyMiddleware</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#用法"><span class="nav-number">1.1.</span> <span class="nav-text">用法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#源码"><span class="nav-number">1.2.</span> <span class="nav-text">源码</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#细节"><span class="nav-number">1.2.1.</span> <span class="nav-text">细节</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#特别的一行代码"><span class="nav-number">1.2.2.</span> <span class="nav-text">特别的一行代码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">1.3.</span> <span class="nav-text">总结</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Mark Lee</span>

  

  
</div>


  


<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" rel="external nofollow" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" rel="external nofollow" href="https://theme-next.org">NexT.Pisces</a> v6.3.0</div>

-->



        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.3.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.3.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.3.0"></script>



  



  










  





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
